import React, { useRef } from "react";
import { Text, TouchableOpacity, View } from "react-native";
import QRCode from "react-native-qrcode-svg";
import styles from "./index.style";
import { useTheme } from "@/contexts/ThemeContext";
import { useUserProfileState } from "@/hooks/user/user-profile";
import { DEFAULT_AVATAR_URL } from "@/config/default-value";
import { saveFileToGallery } from "@/utils/file-utils";

export default function QRCodeView() {
  const { colors } = useTheme();
  const { currentUser } = useUserProfileState();
  const qrCodeRef = useRef<any>(null);

  // 保存二维码到相册
  const saveQRCodeToGallery = async () => {
    if (qrCodeRef.current) {
      console.log(qrCodeRef.current.toDataURL);
      await qrCodeRef.current.toDataURL(async (dataURL: string) => {
        await saveFileToGallery(dataURL);
      });
    }
  };

  return (
    <View style={[styles.qrContainer, { backgroundColor: colors.background }]}>
      {currentUser.id && (
        <QRCode
          getRef={(ref) => (qrCodeRef.current = ref)}
          value={currentUser.id}
          size={200}
          logo={{ uri: currentUser.avatar || DEFAULT_AVATAR_URL }}
          logoSize={50}
          logoBackgroundColor="transparent"
          backgroundColor={colors.background}
          color={colors.text.primary}
        />
      )}
      <Text style={[styles.tip, { color: colors.text.secondary }]}>
        扫一扫上方的二维码增加好友
      </Text>
      <View style={styles.actionsContainer}>
        <TouchableOpacity onPress={saveQRCodeToGallery}>
          <Text style={[styles.actionText, { color: colors.primary }]}>
            保存
          </Text>
        </TouchableOpacity>
        <Text style={[{ color: colors.text.disabled }]}>|</Text>
        <TouchableOpacity onPress={() => console.log("扫一扫")}>
          <Text style={[styles.actionText, { color: colors.primary }]}>
            扫一扫
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}
